<?php
/**
* XMLImporter super class
* use for import data from xml file 
*/
class XMLImporter {
  var $_type ;  //the table name to import
  var $_objData;
  var $_xmlElementName;  //the xml element to parse
  var $_xmlFile; //the xml file name
  var $_error;
  var $_debug;
  function XMLImporter($type = 'Generic' , $element = ''){
    $this->_type = $type;
    $this->_xmlElementName = $element;
    $this->_debug = false;
  }
  function getDataFromFile(){
    if (is_file($this->_xmlFile) && is_readable($this->_xmlFile) && !empty($this->_xmlElementName)){
      Loader::loadClass('SAXReader', "modules/YellowPHP/pnincludes");
      $sax = new SAXReader($this->_xmlFile);
      if ($sax){
        while($sax->isValid()){
          $data = $sax->readNextNode($this->_xmlElementName);
          if ($data){
            $this->_objData[] = $data;
          }else{
            break;
          }
        }
        $sax->close();
        return true;
      }
      $this->_error[] = "ERROR : Could not load class SAXReader";
    }
    $this->_error[] = "ERROR : please check _xmlFile or _xmlElementName";
    return false;
  }
  /**
  * user override
  */
  function importPreProcess(){

  }
  /**
  * user override
  */
  function importPostProcess(){

  }
  /**
  * user override
  */
  function getDataFromFilePreProcess(){

  }
  /**
  * user override
  */
  function getDataFromFilePostProcess(){

  }

  function import(){
    $this->getDataFromFilePreProcess();
    $this->getDataFromFile();
    $this->getDataFromFilePostProcess();
    $this->importPreProcess();
    //loop from _objData
    foreach($this->_objData as $item){
      $res = DBUtil::insertObject($item,$this->_type,'id',true);
      if ($res === false){
        $this->_error[] = "ERROR : can't insert object =>id:" . $item['id'];
      }
    }
    $this->importPostProcess();
  }
}